package com.sqx.modules.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.TbFootprintDao;
import com.sqx.modules.app.entity.TbFootprint;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.brand.dao.BrandDao;
import com.sqx.modules.brand.entity.Brand;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goods.entity.GoodsAndSku;
import com.sqx.modules.goods.entity.SkuIdAndValue;
import com.sqx.modules.goods.service.GoodsAndSkuService;
import com.sqx.modules.goods.service.GoodsService;
import com.sqx.modules.goods.vo.DataJsonVo;
import com.sqx.modules.goods.vo.GoodsVo;
import com.sqx.modules.goodsMessage.service.GoodsMessageService;
import com.sqx.modules.goodsType.dao.GoodsDegreeDao;
import com.sqx.modules.goodsType.dao.GoodsTypeDao;
import com.sqx.modules.goodsType.entity.GoodsDegree;
import com.sqx.modules.goodsType.entity.GoodsType;
import com.sqx.modules.goodsType.service.GoodsTypeService;
import com.sqx.modules.labelType.entity.LabelType;
import com.sqx.modules.labelType.service.LabelTypeService;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.recovery.dao.GoodsSpecificationsDao;
import com.sqx.modules.recovery.entity.AttributeValue;
import com.sqx.modules.recovery.entity.GoodsSpecifications;
import com.sqx.modules.scFollow.entity.ScFollow;
import com.sqx.modules.scFollow.service.ScFollowService;
import com.sqx.modules.scTableColumn.entity.ScTableColumn;
import com.sqx.modules.scTableColumn.service.ScTableColumnService;
import com.sqx.modules.search.service.SearchRecordService;
import com.sqx.modules.sign.dao.GoldRecordsDao;
import com.sqx.modules.sign.entity.GoldRecords;
import com.sqx.modules.stockManage.dao.StockManageDao;
import com.sqx.modules.stockManage.entity.StockManage;
import com.sqx.modules.task.dao.TbDailyTasksDao;
import com.sqx.modules.task.dao.TbUserTaskDao;
import com.sqx.modules.task.entity.TbDailyTasks;
import com.sqx.modules.task.entity.TbUserTask;
import com.sqx.modules.trends.dao.TrendsDao;
import com.sqx.modules.trends.dao.TrendsTypeDao;
import com.sqx.modules.userCertification.entity.UserCertification;
import com.sqx.modules.userCertification.service.UserCertificationService;
import com.sqx.modules.utils.BaiDuUtils;
import jodd.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 商品 服务实现类
 *
 * @author wuChang
 * @since 2024-05-30
 */
@Service
public class GoodsServiceImp extends ServiceImpl<GoodsDao, Goods> implements GoodsService {
    @Autowired
    private UserService userService;
    @Autowired
    private LabelTypeService labelTypeService;
    @Autowired
    private UserCertificationService certificationService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsTypeDao goodsTypeDao;
    @Autowired
    private ScTableColumnService columnService;
    @Autowired
    private GoodsMessageService goodsMessageService;

    @Autowired
    private CommonInfoService commonInfoService;

    @Autowired
    private GoldRecordsDao goldRecordsDao;

    @Autowired
    private TbFootprintDao footprintDao;

    @Autowired
    private ScFollowService followService;

    @Autowired
    private TbUserTaskDao userTaskDao;

    @Autowired
    private TrendsTypeDao trendsTypeDao;

    @Autowired
    private GoodsAndSkuService goodsAndSkuService;

    @Autowired
    private TrendsDao trendsDao;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private GoodsDegreeDao goodsDegreeDao;

    @Autowired
    private GoodsSpecificationsDao goodsSpecificationsDao;

    @Autowired
    private SearchRecordService searchRecordService;

    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;

    @Autowired
    private MessageInfoDao messageInfoDao;

    @Autowired
    private TbDailyTasksDao tbDailyTasksDao;

    @Autowired
    private StockManageDao stockManageDao;

    @Autowired
    private GoodsDao goodsDao;

    private static final Logger logger = LoggerFactory.getLogger(GoodsService.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveGoods(Goods goods) {
        UserCertification certification = certificationService.getOne(new QueryWrapper<UserCertification>().eq("user_id", goods.getUserId()));
        if (certification != null && certification.getStatus() != 1) {
            return Result.error("请先通过实名认证");
        }
        if (goods.getGoodPrice() != null && goods.getGoodPrice().compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("输入商品价格有误，请重新输入");
        }
        if (goods.getFreeMoney() != null && goods.getFreeMoney().compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("输入邮费价格有误，请重新输入");
        }
        if (goods.getIsStock() != null && goods.getIsStock() == 2) {
            if (goods.getStock() != null) {
                if (goods.getStock() < 0) {
                    return Result.error("输入库存有误，请重新输入");
                }
            }
        }
        String value = commonInfoService.findOne(332).getValue();
        if ("2".equals(value)) {
            if (StringUtils.isNotBlank(goods.getGoodTitle())) {
                if (BaiDuUtils.auditBaiDuText(goods.getGoodTitle())) {
                    return Result.error("您发布的内容包含敏感词汇");
                }
            }
            if (StringUtils.isNotBlank(goods.getCoverImg())) {
                if (BaiDuUtils.auditBaiDuImg(goods.getCoverImg())) {
                    return Result.error("您发布的图片不合规");
                }
            }
            if (StringUtils.isNotBlank(goods.getDescImg())) {
                if (BaiDuUtils.auditBaiDuImg(goods.getDescImg())) {
                    return Result.error("您发布的图片不合规");
                }
            }
            if (goods.getGoodId() != null) {
                List<GoodsAndSku> goodsAndSkuList = new ArrayList<>();
                if (goods.getSkuList() != null && !goods.getSkuList().isEmpty()) {
                    for (SkuIdAndValue skuIdStr : goods.getSkuList()) {
                        // 创建 GoodsAndSku 对象
                        GoodsAndSku goodsAndSku = new GoodsAndSku();
                        goodsAndSku.setGoodsId(goods.getGoodId());
                        goodsAndSku.setSkuId(skuIdStr.getSkuId());
                        goodsAndSku.setSkuValue(skuIdStr.getSkuValue());
                        goodsAndSkuList.add(goodsAndSku);
                        // 删除旧的 GoodsAndSku 记录
                        goodsAndSkuService.deleteByGoodsId(goods.getGoodId());
                    }
                    // 去除重复项
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .distinct()
                            .collect(Collectors.toList());

                    // 过滤掉无效的 skuId
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .filter(goodsAndSku -> goodsAndSku.getSkuId() != null && !goodsAndSku.getSkuId().equals(0L))
                            .collect(Collectors.toList());
                    if (goodsAndSkuList.isEmpty()) {
                        return Result.error("请选择商品规格");
                    }

                    // 批量保存规格和子规格id
                    goodsAndSkuService.saveBatch(goodsAndSkuList);
                }
                goods.setStatus(1);
                if (goods.getIsStock() != null && goods.getIsStock() == 2) {
                    goods.setStock(goods.getStock());
                } else {
                    goods.setIsStock(1);
                    goods.setStock(1);
                }
                if (goods.getTypeId() != null) {
                    GoodsType goodsType = goodsTypeDao.selectById(goods.getTypeId());
                    if (goodsType != null) {
                        LabelType labelType = labelTypeService.getById(goodsType.getLabelId());
                        if (labelType != null) {
                            goods.setLabelId(labelType.getLabelId());
                        }
                    }
                }
                if (goods.getStockId() != null) {
                    StockManage stockManage = stockManageDao.selectById(goods.getStockId());
                    if (stockManage.getStock() != null && stockManage.getStock() < goods.getStock()) {
                        return Result.error("发布商品库存不能大于回收库存管理");
                    }
                    if (stockManage.getStock() != null && stockManage.getStock() != 0) {
                        stockManage.setStock(stockManage.getStock() - goods.getStock());
                    }
                    stockManageDao.updateById(stockManage);
                    goods.setStock(goods.getStock());
                }
                return Result.upStatus(baseMapper.updateById(goods));
            } else if (goods.getGoodStatus() == 1) {
                goods.setCreateTime(LocalDateTime.now());
                goods.setIsEnable(1);
                goods.setBrowseCount(0);
                goods.setStatus(1);
                goods.setGoodStatus(1);
                goods.setRecycleStatus(2);
                int result = baseMapper.insert(goods);
                if (result > 0) {
                    List<GoodsAndSku> goodsAndSkuList = new ArrayList<>();
                    if (goods.getSkuList() != null && !goods.getSkuList().isEmpty()) {
                        for (SkuIdAndValue skuIdStr : goods.getSkuList()) {
                            // 创建 GoodsAndSku 对象
                            GoodsAndSku goodsAndSku = new GoodsAndSku();
                            goodsAndSku.setGoodsId(goods.getGoodId());
                            goodsAndSku.setSkuId(skuIdStr.getSkuId());
                            goodsAndSku.setSkuValue(skuIdStr.getSkuValue());
                            goodsAndSkuList.add(goodsAndSku);
                        }
                        // 去除重复项
                        goodsAndSkuList = goodsAndSkuList.stream()
                                .distinct()
                                .collect(Collectors.toList());

                        // 过滤掉无效的 skuId
                        goodsAndSkuList = goodsAndSkuList.stream()
                                .filter(goodsAndSku -> goodsAndSku.getSkuId() != null && !goodsAndSku.getSkuId().equals(0L))
                                .collect(Collectors.toList());
                        if (goodsAndSkuList.isEmpty()) {
                            return Result.error("请选择商品规格");
                        }
                        // 批量保存规格和子规格id
                        goodsAndSkuService.saveBatch(goodsAndSkuList);
                    }
                    // 初始化总价格
                    BigDecimal totalPrice = BigDecimal.ZERO;
                    //查询商品规格信息关联信息
                    List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                            .eq("goods_id", goods.getGoodId()));
                    //解析规格信息
                    if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
                        for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                            GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                            if (goodsSpecifications != null) {
                                String attributeValues = goodsSpecifications.getAttributeValue();
                                // 使用正则表达式修正字符串中的单引号为双引号
                                attributeValues = attributeValues.replaceAll("'", "\"");
                                // 使用正则表达式将等号替换为冒号
                                attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                                List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                                goodsSpecifications.setAttributes(attributeValuesList);
                                // 解析 sku_value 字段得到一组 attribute_value 的 ID
                                String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                                List<AttributeValue> filteredAttributes = new ArrayList<>();
                                for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                                    if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                        attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                        filteredAttributes.add(attribute);
                                    }
                                }
                                // 将所有商品规格价格相加
                                BigDecimal skuTotalPrice = filteredAttributes.stream()
                                        .map(attr -> new BigDecimal(attr.getAttPrice()))
                                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                                // 累加到总价格
                                totalPrice = totalPrice.add(skuTotalPrice);
                                log.error("SKU ID:" + goodsAndSku.getSkuId());
                                log.error("SKU Total Price:" + skuTotalPrice);
                            }
                        }
                        int code = updateByTotalPrice(goods.getGoodId(), totalPrice);
                        if (code == 1) {
                            return Result.success().put("data", goods.getGoodId()).put("totalPrice", totalPrice);
                        }
//                        goods.setGoodPrice(totalPrice);
//                        goodsDao.updateByGoodId(goods);
                        return Result.success().put("data", goods.getGoodId()).put("totalPrice", totalPrice);
                    }
                } else {
                    return Result.error("估价失败");
                }
            } else {
                goods.setCreateTime(LocalDateTime.now());
                goods.setIsEnable(1);
                goods.setBrowseCount(0);
                goods.setStatus(1);
                if (goods.getDelivery() == 1 || goods.getDelivery() == 2) {
                    goods.setFreeMoney(BigDecimal.ZERO);
                }
                if (goods.getIsStock() != null && goods.getIsStock() == 2) {
                    goods.setStock(goods.getStock());
                } else {
                    goods.setIsStock(1);
                    goods.setStock(1);
                }
                baseMapper.insert(goods);
                if (goods.getTaskId() != null) {
                    TbDailyTasks tbDailyTasks = tbDailyTasksDao.selectById(goods.getTaskId());
                    if (tbDailyTasks != null) {
                        Integer gold = tbDailyTasks.getSpecies();
                        TbUserTask tbUserTask1 = new TbUserTask();
                        tbUserTask1.setTaskId(goods.getTaskId());
                        tbUserTask1.setUserId(goods.getUserId());
                        tbUserTask1.setState(1);
                        tbUserTask1.setCreateTime(new Date());
                        tbUserTask1.setRewardClaimed(1);
                        userTaskDao.insert(tbUserTask1);
                        UserEntity userEntity = userService.selectUserById(goods.getUserId());
                        if (userEntity != null) {
                            userEntity.setTotalGold(userEntity.getTotalGold() + gold);
                            userService.updateById(userEntity);
                        }
                        GoldRecords goldRecords = new GoldRecords();
                        goldRecords.setGoldChange(1);
                        goldRecords.setGoldCoins(gold);
                        goldRecords.setRemark("发布商品奖励");
                        goldRecords.setUserId(goods.getUserId());
                        goldRecords.setCreateTime(new Date());
                        goldRecordsDao.insert(goldRecords);
                    }
                }
                List<GoodsAndSku> goodsAndSkuList = new ArrayList<>();
                if (goods.getSkuList() != null && !goods.getSkuList().isEmpty()) {
                    for (SkuIdAndValue skuIdStr : goods.getSkuList()) {
                        // 创建 GoodsAndSku 对象
                        GoodsAndSku goodsAndSku = new GoodsAndSku();
                        goodsAndSku.setGoodsId(goods.getGoodId());
                        goodsAndSku.setSkuId(skuIdStr.getSkuId());
                        goodsAndSku.setSkuValue(skuIdStr.getSkuValue());
                        goodsAndSkuList.add(goodsAndSku);
                    }
                    // 去除重复项
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .distinct()
                            .collect(Collectors.toList());

                    // 过滤掉无效的 skuId
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .filter(goodsAndSku -> goodsAndSku.getSkuId() != null && !goodsAndSku.getSkuId().equals(0L))
                            .collect(Collectors.toList());
                    if (goodsAndSkuList.isEmpty()) {
                        return Result.error("请选择商品规格");
                    }
                    // 批量保存规格和子规格id
                    goodsAndSkuService.saveBatch(goodsAndSkuList);
                }
            }
            return Result.success().put("data", goods.getGoodId());
        } else {
//        switch (checkTableData(goods.getDataJson(), goods.getTypeId())) {
//            case 0:
//                break;
//            case 1:
//                return Result.error("分类不存在");
//            case 2:
//                return Result.error("提交的字段有不是模板中包含的字段");
//            case 3:
//                return Result.error("提交的字段缺少模板中需要的字段");
//            case 4:
//                return Result.error("必填字段为空");
//        }

//        List<ScTableColumn> classList = columnService.list(new QueryWrapper<ScTableColumn>().eq("type_id", goods.getTypeId()));
//        List<DataJsonVo> dataJson = goods.getDataJson();
//        for (DataJsonVo dataJsonVo : dataJson) {
//            for (ScTableColumn tableColumn : classList) {
//                if (dataJsonVo.getHtmlType() == 2 || dataJsonVo.getHtmlType() == 3 || dataJsonVo.getHtmlType() == 4 || dataJsonVo.getHtmlType() == 5) {
//                    if (dataJsonVo.getColumnName().equals(tableColumn.getColumnName())) {
//                        dataJsonVo.setOptionJson(tableColumn.getOptionJson());
//                    }
//                }
//            }
//        }
//        goods.setDataJson(dataJson);
            if (goods.getGoodId() != null) {
                List<GoodsAndSku> goodsAndSkuList = new ArrayList<>();
                if (goods.getSkuList() != null && !goods.getSkuList().isEmpty()) {
                    for (SkuIdAndValue skuIdStr : goods.getSkuList()) {
                        // 创建 GoodsAndSku 对象
                        GoodsAndSku goodsAndSku = new GoodsAndSku();
                        goodsAndSku.setGoodsId(goods.getGoodId());
                        goodsAndSku.setSkuId(skuIdStr.getSkuId());
                        goodsAndSku.setSkuValue(skuIdStr.getSkuValue());
                        goodsAndSkuList.add(goodsAndSku);
                        // 删除旧的 GoodsAndSku 记录
                        goodsAndSkuService.deleteByGoodsId(goods.getGoodId());
                    }
                    // 去除重复项
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .distinct()
                            .collect(Collectors.toList());

                    // 过滤掉无效的 skuId
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .filter(goodsAndSku -> goodsAndSku.getSkuId() != null && !goodsAndSku.getSkuId().equals(0L))
                            .collect(Collectors.toList());
                    if (goodsAndSkuList.isEmpty()) {
                        return Result.error("请选择商品规格");
                    }
                    // 批量保存规格和子规格id
                    goodsAndSkuService.saveBatch(goodsAndSkuList);
                }
                if (goods.getIsStock() != null && goods.getIsStock() == 2) {
                    goods.setStock(goods.getStock());
                } else {
                    goods.setIsStock(1);
                    goods.setStock(1);
                }
                if (goods.getTypeId() != null) {
                    GoodsType goodsType = goodsTypeDao.selectById(goods.getTypeId());
                    if (goodsType != null) {
                        LabelType labelType = labelTypeService.getById(goodsType.getLabelId());
                        if (labelType != null) {
                            goods.setLabelId(labelType.getLabelId());
                        }
                    }
                }
                if (goods.getStockId() != null) {
                    StockManage stockManage = stockManageDao.selectById(goods.getStockId());
                    if (stockManage.getStock() != null && stockManage.getStock() < goods.getStock()) {
                        return Result.error("发布商品库存不能大于回收库存管理");
                    }
                    if (stockManage.getStock() != null && stockManage.getStock() != 0) {
                        stockManage.setStock(stockManage.getStock() - goods.getStock());
                    }
                    stockManageDao.updateById(stockManage);
                    goods.setStock(goods.getStock());
                }
                return Result.upStatus(baseMapper.updateById(goods));
            } else if (goods.getGoodStatus() == 1) {
                goods.setCreateTime(LocalDateTime.now());
                goods.setIsEnable(0);
                goods.setBrowseCount(0);
                goods.setStatus(0);
                goods.setGoodStatus(1);
                goods.setRecycleStatus(2);
                int result = baseMapper.insert(goods);
                if (result > 0) {
                    List<GoodsAndSku> goodsAndSkuList = new ArrayList<>();
                    if (goods.getSkuList() != null && !goods.getSkuList().isEmpty()) {
                        for (SkuIdAndValue skuIdStr : goods.getSkuList()) {
                            // 创建 GoodsAndSku 对象
                            GoodsAndSku goodsAndSku = new GoodsAndSku();
                            goodsAndSku.setGoodsId(goods.getGoodId());
                            goodsAndSku.setSkuId(skuIdStr.getSkuId());
                            goodsAndSku.setSkuValue(skuIdStr.getSkuValue());
                            goodsAndSkuList.add(goodsAndSku);
                        }
                        // 去除重复项
                        goodsAndSkuList = goodsAndSkuList.stream()
                                .distinct()
                                .collect(Collectors.toList());

                        // 过滤掉无效的 skuId
                        goodsAndSkuList = goodsAndSkuList.stream()
                                .filter(goodsAndSku -> goodsAndSku.getSkuId() != null && !goodsAndSku.getSkuId().equals(0L))
                                .collect(Collectors.toList());
                        if (goodsAndSkuList.isEmpty()) {
                            return Result.error("请选择商品规格");
                        }
                        // 批量保存规格和子规格id
                        goodsAndSkuService.saveBatch(goodsAndSkuList);
                    }
                    // 初始化总价格
                    BigDecimal totalPrice = BigDecimal.ZERO;
                    //查询商品规格信息关联信息
                    List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                            .eq("goods_id", goods.getGoodId()));
                    //解析规格信息
                    if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
                        for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                            GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                            if (goodsSpecifications != null) {
                                String attributeValues = goodsSpecifications.getAttributeValue();
                                // 使用正则表达式修正字符串中的单引号为双引号
                                attributeValues = attributeValues.replaceAll("'", "\"");
                                // 使用正则表达式将等号替换为冒号
                                attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                                List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                                goodsSpecifications.setAttributes(attributeValuesList);
                                // 解析 sku_value 字段得到一组 attribute_value 的 ID
                                String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                                List<AttributeValue> filteredAttributes = new ArrayList<>();
                                for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                                    if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                        attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                        filteredAttributes.add(attribute);
                                    }
                                }
                                // 将所有商品规格价格相加
                                BigDecimal skuTotalPrice = filteredAttributes.stream()
                                        .map(attr -> new BigDecimal(attr.getAttPrice()))
                                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                                // 累加到总价格
                                totalPrice = totalPrice.add(skuTotalPrice);
                                log.error("SKU ID:" + goodsAndSku.getSkuId());
                                log.error("SKU Total Price:" + skuTotalPrice);
                            }
                        }
                        updateByTotalPrice(goods.getGoodId(), totalPrice);
                        return Result.success().put("data", goods.getGoodId()).put("totalPrice", totalPrice);
                    }
                } else {
                    return Result.error("估价失败");
                }
            } else {
                goods.setCreateTime(LocalDateTime.now());
                goods.setIsEnable(0);
                goods.setBrowseCount(0);
                goods.setStatus(0);
                goods.setGoodStatus(0);
                if (goods.getDelivery() == 1 || goods.getDelivery() == 2) {
                    goods.setFreeMoney(BigDecimal.ZERO);
                }
                if (goods.getIsStock() != null && goods.getIsStock() == 2) {
                    goods.setStock(goods.getStock());
                } else {
                    goods.setIsStock(1);
                    goods.setStock(1);
                }
                baseMapper.insert(goods);
                List<GoodsAndSku> goodsAndSkuList = new ArrayList<>();
                if (goods.getSkuList() != null && !goods.getSkuList().isEmpty()) {
                    for (SkuIdAndValue skuIdStr : goods.getSkuList()) {
                        // 创建 GoodsAndSku 对象
                        GoodsAndSku goodsAndSku = new GoodsAndSku();
                        goodsAndSku.setGoodsId(goods.getGoodId());
                        goodsAndSku.setSkuId(skuIdStr.getSkuId());
                        goodsAndSku.setSkuValue(skuIdStr.getSkuValue());
                        goodsAndSkuList.add(goodsAndSku);
                    }
                    // 去除重复项
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .distinct()
                            .collect(Collectors.toList());

                    // 过滤掉无效的 skuId
                    goodsAndSkuList = goodsAndSkuList.stream()
                            .filter(goodsAndSku -> goodsAndSku.getSkuId() != null && !goodsAndSku.getSkuId().equals(0L))
                            .collect(Collectors.toList());
                    if (goodsAndSkuList.isEmpty()) {
                        return Result.error("请选择商品规格");
                    }
                    // 批量保存规格和子规格id
                    goodsAndSkuService.saveBatch(goodsAndSkuList);
                }
            }
            return Result.success().put("data", goods.getGoodId());
        }
    }

    private int updateByTotalPrice(Long goodId, BigDecimal totalPrice) {
        int result = goodsDao.updateByGoodId(goodId, totalPrice);
        if (result <= 0) {
            return 0;
        }
        return 1;
    }

    /**
     * 检测提交的参数是否符合模板字段。
     *
     * @return 0=正确 1=分类不存在 2提交的参数字段不是模板下定义的字段 3 提交的参数字段缺少模板定义的字段(不是必填的,可以为空,但必须传) 4模板必填字段为空
     */
    private Integer checkTableData(List<DataJsonVo> dataJson, Long typeId) {
        //校验提交的分类是否存在
        GoodsType goodsType = goodsTypeService.getOne(new QueryWrapper<GoodsType>().eq("type_id", typeId));
        if (goodsType == null) {
            return 1;
        }
        List<ScTableColumn> tableColumnList = columnService.list(new QueryWrapper<ScTableColumn>().eq("type_id", typeId));
        //校验提交的参数是否是分类下模板定义的字段。
        for (DataJsonVo dataJsonVo : dataJson) {
            List<ScTableColumn> columns = columnService.list(new QueryWrapper<ScTableColumn>().eq("column_name", dataJsonVo.getColumnName()).eq("type_id", typeId));
            if (columns.size() <= 0) {
                log.error("提交的参数中字段" + dataJsonVo.getColumnName() + "不存在!");
                return 2;
            }
        }
        //校验提交的参数是否符合模板字段
        for (ScTableColumn tableColumn : tableColumnList) {
            if (!checkColumn(tableColumn.getColumnName(), dataJson)) {
                log.error("提交的参数中缺少字段" + tableColumn.getColumnName());
                return 3;
            }
        }
        //校验模板必填字段是否为空
        for (ScTableColumn tableColumn : tableColumnList) {
            for (DataJsonVo dataJsonVo : dataJson) {
                if (tableColumn.getColumnName().equals(dataJsonVo.getColumnName())) {
                    if (tableColumn.getIsRequired() == 1) {
                        if (StringUtils.isBlank(dataJsonVo.getColumnValue())) {
                            log.error("提交的参数中字段" + dataJsonVo.getColumnName() + "不能为空!");
                            return 4;
                        }
                    }
                }
            }
        }


        return 0;
    }

    /**
     * 校验提交的参数字段是否包含模板的字段。
     *
     * @param columnName 模板字段
     * @param dataJson   提交的字段
     * @return
     */
    private boolean checkColumn(String columnName, List<DataJsonVo> dataJson) {
        for (DataJsonVo dataJsonVo : dataJson) {
            if (columnName.equals(dataJsonVo.getColumnName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public IPage<Goods> getMyGoodsList(Integer page, Integer limit, Goods goods) {
        Page<Goods> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getMyGoodsList(pages, goods);
    }

    @Override
    public Result updateStatus(Long userId, Long goodId) {
        Goods goods = baseMapper.selectById(goodId);
        if (goods == null) {
            return Result.error("商品不存在");
        }
        if (userId != null) {
            UserEntity userEntity = userService.getById(userId);
            if (!goods.getUserId().equals(userEntity.getUserId())) {
                return Result.error("无权操作");
            }
        }
        if (goods.getIsEnable() == 0) {
            if (goods.getStatus() == 0 || goods.getStatus() == 2) {
                return Result.error("请先通过审核");
            }
            if (goods.getStatus() == 3) {
                return Result.error("当前商品已售空");
            }
            if (goods.getStatus() == 4) {
                return Result.error("商品已封禁");
            }
            goods.setIsEnable(1);
        } else {
            goods.setIsEnable(0);
        }
        return Result.upStatus(baseMapper.updateById(goods));

    }

    @Override
    public IPage<GoodsVo> getAdminGoodsList(Integer page, Integer limit, GoodsVo goodsVo) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<GoodsVo> goodsVoIPage = baseMapper.getAdminGoodsList(pages, goodsVo);
        for (GoodsVo record : goodsVoIPage.getRecords()) {
            GoodsType goodsType = goodsTypeService.getById(record.getTypeId());
            if (goodsType != null) {
                if (goodsType.getTypeName().equals("手机类")) {
                    record.setFirstTypeId(goodsType.getTypeId());
                    record.setFirstTypeName(goodsType.getTypeName());
                    record.setTypeId(null);
                    record.setTypeName(null);
                }
                GoodsType parentGoodsType = goodsTypeService.getById(goodsType.getParentId());
                if (parentGoodsType != null) {
                    record.setFirstTypeId(parentGoodsType.getTypeId());
                    record.setFirstTypeName(parentGoodsType.getTypeName());
                }
            }
        }
        return goodsVoIPage;
    }

    @Override
    public IPage<GoodsVo> getAdminRecycleGoodsList(Integer page, Integer limit, GoodsVo goodsVo) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<GoodsVo> goodsVoIPage = baseMapper.getRecycleGoodsList(pages, goodsVo);
        for (GoodsVo record : goodsVoIPage.getRecords()) {
            GoodsType goodsType = goodsTypeService.getById(record.getTypeId());
            if (goodsType != null) {
                if (goodsType.getTypeName().equals("手机类")) {
                    record.setFirstTypeId(goodsType.getTypeId());
                    record.setFirstTypeName(goodsType.getTypeName());
                    record.setTypeId(null);
                    record.setTypeName(null);
                }
                GoodsType parentGoodsType = goodsTypeService.getById(goodsType.getParentId());
                if (parentGoodsType != null) {
                    record.setFirstTypeId(parentGoodsType.getTypeId());
                    record.setFirstTypeName(parentGoodsType.getTypeName());
                }
            }
        }
        return goodsVoIPage;
    }

    @Override
    public Result authGoods(Long goodId, Integer status, String authRemark) {
        Goods goods = baseMapper.selectById(goodId);
        if (goods == null) {
            return Result.error("商品已存在");
        }
        if (status == 1) {
            goods.setStatus(1);
            goods.setIsEnable(1);
//            UserEntity userEntity = userService.getById(goods.getUserId());
//            if (userEntity != null) {
//                // 新增实名认证通过后增加金币的记录
//                GoldRecords goldRecords = new GoldRecords();
//                goldRecords.setUserId(userEntity.getUserId());
//                goldRecords.setGoldChange(1);
//                goldRecords.setRemark("商品发布成功奖励");
//                goldRecords.setCreateTime(new Date());
//                goldRecords.setRelatedId(goods.getGoodId());
//                goldRecords.setGoldCoins(Integer.valueOf(commonInfoService.findOne(510).getValue()));
//                goldRecordsDao.insert(goldRecords);
//                userEntity.setTotalGold(userEntity.getTotalGold() + Integer.valueOf(commonInfoService.findOne(510).getValue()));
//                userService.updateById(userEntity);
//            }
            if (goods.getTaskId() != null) {
                TbDailyTasks tbDailyTasks = tbDailyTasksDao.selectById(goods.getTaskId());
                if (tbDailyTasks != null) {
                    Integer gold = tbDailyTasks.getSpecies();
                    TbUserTask tbUserTask1 = new TbUserTask();
                    tbUserTask1.setTaskId(goods.getTaskId());
                    tbUserTask1.setUserId(goods.getUserId());
                    tbUserTask1.setState(1);
                    tbUserTask1.setCreateTime(new Date());
                    tbUserTask1.setRewardClaimed(1);
                    userTaskDao.insert(tbUserTask1);
                    UserEntity userEntity = userService.selectUserById(goods.getUserId());
                    if (userEntity != null) {
                        userEntity.setTotalGold(userEntity.getTotalGold() + gold);
                        userService.updateById(userEntity);
                    }
                    GoldRecords goldRecords = new GoldRecords();
                    goldRecords.setGoldChange(1);
                    goldRecords.setGoldCoins(gold);
                    goldRecords.setRemark("发布商品奖励");
                    goldRecords.setUserId(goods.getUserId());
                    goldRecords.setCreateTime(new Date());
                    goldRecordsDao.insert(goldRecords);
                }
            }
        } else {
            goods.setStatus(2);
            UserEntity userEntity = userService.selectUserById(goods.getUserId());
            if (userEntity != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setTitle("您的商品审核未通过，商品：" + goods.getGoodTitle());
                messageInfo.setContent("商品审核未通过，请查看");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setState(String.valueOf(6));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfoDao.insert(messageInfo);
            }
        }
        goods.setAuthRemark(authRemark);
        return Result.upStatus(baseMapper.updateById(goods));
    }

    @Override
    public Result banGoods(Long goodId, String authRemark) {
        Goods goods = baseMapper.selectById(goodId);
        if (goods == null) {
            return Result.error("商品已存在");
        }
        if (goods.getStatus() != 4) {
            goods.setStatus(4);
            UserEntity userEntity = userService.selectUserById(goods.getUserId());
            if (userEntity != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setTitle("您的商品已被封禁，商品：" + goods.getGoodTitle());
                messageInfo.setContent("商品已被封禁，请查看");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setStatus(0);
                messageInfo.setState(String.valueOf(6));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfoDao.insert(messageInfo);
            }
        } else {
            goods.setStatus(1);
        }
        goods.setAuthRemark(authRemark);

        return Result.upStatus(baseMapper.updateById(goods));
    }

    @Override
    public IPage<GoodsVo> getGoodsList(Integer page, Integer limit, GoodsVo goodsVo) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        if (goodsVo.getLabelId() == null && goodsVo.getTypeId() == null) {
            // searchType 1.综合排序
            if (goodsVo.getSearchType() != null) {
                if (StringUtils.isNotBlank(goodsVo.getProvince()) || StringUtils.isNotBlank(goodsVo.getCity()) || StringUtils.isNotBlank(goodsVo.getDistrict())) {
//                    // 查找"市"
//                    int cityEnd = goodsVo.getRegionalDetails().indexOf("市");
//                    String city = "";
//                    if (cityEnd != -1){
//                        city = goodsVo.getRegionalDetails().substring(0, cityEnd + 1);// "包含市"
//                    }
//                    int distinctEnd = Math.max(goodsVo.getRegionalDetails().indexOf("区"), goodsVo.getRegionalDetails().indexOf("县"));
//                    String district = "";
//                    if (distinctEnd != -1){
//                        district = goodsVo.getRegionalDetails().substring(cityEnd + 1, distinctEnd + 1);
//                    }
                    goodsVo.setProvince(goodsVo.getProvince());
                    goodsVo.setCity(goodsVo.getCity());
                    goodsVo.setDistrict(goodsVo.getDistrict());
                }
                return baseMapper.getGoodsBySearchList(pages, goodsVo);
            }
//            if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 1) {
//                // subSearchType 1.最近活跃
//                if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // subSearchType 2.离我最近
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 2) {
//                    // longitude经度 latitude纬度
//                    if (goodsVo.getLongitude() != null || goodsVo.getLatitude() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                    // subSearchType 3.信用排序
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 2.时间排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 2) {
//                // timeRange 1.近一周
//                if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 2.近7天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 3.近15天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 4.近30天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 4) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 5.本周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 5) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 6.上周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 6) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 7.本月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 7) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 8.上月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 8) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 9.自定义时间
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 9) {
//                    if (goodsVo.getStartDate() != null && goodsVo.getEndDate() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                }
//                // searchType 3.价格排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 3) {
//                // priceOrder 1.升序
//                if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // priceOrder 2.降序
//                } else if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 4.区域排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 4) {
//                // city市 district区
//                if (goodsVo.getLongitude() != null && goodsVo.getLatitude() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//            }
//            if (goodsVo.getUserId() != null) {
//                searchRecordService.saveRecordInfo(goodsVo.getBrandName(), goodsVo.getUserId());
//            }
//            goodsVo.setUserId(null);
//            return baseMapper.getGoodsByIsRecommend(pages, goodsVo);
//        } else {
//            // searchType 1.综合排序
//            if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 1) {
//                // subSearchType 1.最近活跃
//                if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // subSearchType 2.离我最近
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 2) {
//                    // longitude经度 latitude纬度
//                    if (goodsVo.getLongitude() != null || goodsVo.getLatitude() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                    // subSearchType 3.信用排序
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 2.时间排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 2) {
//                // timeRange 1.近一周
//                if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 2.近7天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 3.近15天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 4.近30天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 4) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 5.本周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 5) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 6.上周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 6) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 7.本月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 7) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 8.上月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 8) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 9.自定义时间
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 9) {
//                    if (goodsVo.getStartDate() != null && goodsVo.getEndDate() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                }
//                // searchType 3.价格排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 3) {
//                // priceOrder 1.升序
//                if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // priceOrder 2.降序
//                } else if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 4.区域排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 4) {
//                // city市 district区
//                if (goodsVo.getLongitude() != null && goodsVo.getLatitude() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
            if (goodsVo.getIsRecommend() != null && goodsVo.getIsRecommend() == 1) {
                return baseMapper.getGoodListByIsRecommend(pages, goodsVo);
            }
            return baseMapper.getGoodsList(pages, goodsVo);
        }
        if (goodsVo.getUserId() != null) {
            searchRecordService.saveRecordInfo(goodsVo.getBrandName(), goodsVo.getUserId());
        }
        goodsVo.setUserId(null);
        if (goodsVo.getSearchType() != null) {
            if (StringUtils.isNotBlank(goodsVo.getProvince()) || StringUtils.isNotBlank(goodsVo.getCity()) || StringUtils.isNotBlank(goodsVo.getDistrict())) {
//                    // 查找"市"
//                    int cityEnd = goodsVo.getRegionalDetails().indexOf("市");
//                    String city = "";
//                    if (cityEnd != -1){
//                        city = goodsVo.getRegionalDetails().substring(0, cityEnd + 1);// "包含市"
//                    }
//                    int distinctEnd = Math.max(goodsVo.getRegionalDetails().indexOf("区"), goodsVo.getRegionalDetails().indexOf("县"));
//                    String district = "";
//                    if (distinctEnd != -1){
//                        district = goodsVo.getRegionalDetails().substring(cityEnd + 1, distinctEnd + 1);
//                    }
                goodsVo.setProvince(goodsVo.getProvince());
                goodsVo.setCity(goodsVo.getCity());
                goodsVo.setDistrict(goodsVo.getDistrict());
            }
            return baseMapper.getGoodsBySearchList(pages, goodsVo);
        }
        goodsVo.setUserId(null);
        return baseMapper.getGoodsList(pages, goodsVo);
    }

    @Override
    public Result getGoodsById(Long goodId, Long loginUserId) {
        GoodsVo goodsVo = baseMapper.getGoodsById(goodId, loginUserId);
        if (goodsVo == null) {
            return Result.error("商品不存在");
        }
        //查询商品规格信息关联信息
        List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                .eq("goods_id", goodId));
        //解析规格信息
        List<GoodsSpecifications> specificationsList = new ArrayList<>();
        if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
            for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                if (goodsSpecifications != null) {
                    String attributeValues = goodsSpecifications.getAttributeValue();
                    // 使用正则表达式修正字符串中的单引号为双引号
                    attributeValues = attributeValues.replaceAll("'", "\"");
                    // 使用正则表达式将等号替换为冒号
                    attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                    List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                    goodsSpecifications.setAttributes(attributeValuesList);
                    // 解析 sku_value 字段得到一组 attribute_value 的 ID
                    String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                    List<AttributeValue> filteredAttributes = new ArrayList<>();
                    for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                        if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                            attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                            filteredAttributes.add(attribute);
                        }
                    }
                    // 将所有商品规格价格相加，存入这个字段
                    BigDecimal totalPrice = filteredAttributes.stream()
                            .map(attr -> new BigDecimal(attr.getAttPrice()))
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    goodsVo.setGoodPrice(totalPrice);
                    // 设置过滤后的属性值列表
                    goodsSpecifications.setAttributes(filteredAttributes);
                    // 添加到最终的规格列表中
                    specificationsList.add(goodsSpecifications);
                }
            }
            // 将规格信息添加到 GoodsVo 中
            goodsVo.setSpecifications(specificationsList);
        }
        goodsVo.setBrowseCount(goodsVo.getBrowseCount() + 1);
        baseMapper.updateById(goodsVo);
        if (!ObjectUtils.isEmpty(goodsVo)) {
            if (loginUserId != null && !goodsVo.getUserId().equals(loginUserId)) {
                // 记录浏览足迹
                TbFootprint tbFootprint = new TbFootprint();
                tbFootprint.setGoodId(goodId);
                tbFootprint.setUserId(loginUserId);
                tbFootprint.setVisitTime(new Date());
                footprintDao.insert(tbFootprint);
            }
        }
        return Result.success().put("data", goodsVo);
    }

    @Override
    public Result getAppGoodsById(Long userId, Long goodId, Long loginUserId) {
        GoodsVo goodsVo = baseMapper.getGoodsById(goodId, loginUserId);
        if (goodsVo == null) {
            return Result.error("商品不存在");
        }
        if (goodsVo.getTypeId() != null) {
            GoodsType goodsType = goodsTypeDao.selectById(goodsVo.getTypeId());
            GoodsType firstType = goodsTypeDao.selectById(goodsType.getParentId());
            if (firstType != null) {
                goodsVo.setFirstTypeId(firstType.getTypeId());
            }
        }
        //查询商品规格信息关联信息
        List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                .eq("goods_id", goodId));
        //解析规格信息
        List<GoodsSpecifications> specificationsList = new ArrayList<>();
        if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
            for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                if (goodsSpecifications != null) {
                    String attributeValues = goodsSpecifications.getAttributeValue();
                    // 使用正则表达式修正字符串中的单引号为双引号
                    attributeValues = attributeValues.replaceAll("'", "\"");
                    // 使用正则表达式将等号替换为冒号
                    attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                    List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                    goodsSpecifications.setAttributes(attributeValuesList);
                    // 解析 sku_value 字段得到一组 attribute_value 的 ID
                    String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                    List<AttributeValue> filteredAttributes = new ArrayList<>();
                    for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                        if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                            attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                            filteredAttributes.add(attribute);
                        }
                    }
                    if (goodsVo.getGoodStatus() == 1) {
                        // 将所有商品规格价格相加，存入这个字段
                        BigDecimal totalPrice = filteredAttributes.stream()
                                .map(attr -> new BigDecimal(attr.getAttPrice()))
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        goodsVo.setGoodPrice(totalPrice);
                    }
                    // 设置过滤后的属性值列表
                    goodsSpecifications.setAttributes(filteredAttributes);
                    // 添加到最终的规格列表中
                    specificationsList.add(goodsSpecifications);
                }
            }
            // 将规格信息添加到 GoodsVo 中
            goodsVo.setSpecifications(specificationsList);
        }
        goodsVo.setBrowseCount(goodsVo.getBrowseCount() + 1);
        baseMapper.updateById(goodsVo);
        if (!ObjectUtils.isEmpty(goodsVo)) {
            if (loginUserId != null && !goodsVo.getUserId().equals(loginUserId)) {
                // 记录浏览足迹
                TbFootprint tbFootprint = new TbFootprint();
                tbFootprint.setGoodId(goodId);
                tbFootprint.setUserId(loginUserId);
                tbFootprint.setVisitTime(new Date());
                footprintDao.insert(tbFootprint);
            }
        }
        return Result.success().put("data", goodsVo);
    }

    @Override
    public Result getGoodsByCoordinates(Long typeId, Integer pageNum, Integer pageSize, GoodsVo goodsVo) {
        if (goodsVo.getLat() != null && goodsVo.getLng() != null) {
            Page<GoodsVo> pages;
            if (pageNum != null && pageSize != null) {
                pages = new Page<>(pageNum, pageSize);
            } else {
                pages = new Page<>();
                pages.setSize(-1);
            }
            if (goodsVo.getTypeId() == null) {
                List<ScFollow> scFollows = trendsTypeDao.selectByUserId(goodsVo.getUserId());
                List<TbFootprint> footprintList = trendsTypeDao.selectByFootprintList(goodsVo.getUserId());
                // 用于存放用户已知的商品ID
                Set<Long> allGoodIds = new HashSet<>();
                // 用于存放商品类型ID
                Set<Long> typeIds = new HashSet<>();
//            Set<Long> allGoodIds = new HashSet<>();
                // 提取收藏的商品ID到Set中和类型ID
                if (scFollows != null && !scFollows.isEmpty()) {
                    scFollows.forEach(scFollow -> {
                        allGoodIds.add(scFollow.getById());
                    });
                    // 批量获取类型ID
                    List<Long> followTypeIds = baseMapper.getTypeIdsByGoodIds(new ArrayList<>(allGoodIds));
                    typeIds.addAll(followTypeIds);
                }
                // 从浏览过的商品中提取商品ID和类型ID
                if (footprintList != null && !footprintList.isEmpty()) {
                    footprintList.forEach(footprint -> {
                        allGoodIds.add(footprint.getGoodId());
                    });
                    // 批量获取类型ID
                    List<Long> footprintTypeIds = baseMapper.getTypeIdsByGoodIds(new ArrayList<>(allGoodIds));
                    typeIds.addAll(footprintTypeIds);
                }

                // 查询类型下除了已知商品外的其他新商品
                return Result.success().put("data", baseMapper.getGoodsByTypeExcludingId(pages, typeIds, allGoodIds, goodsVo));
//                IPage<Goods> goodsList = baseMapper.getGoodsByCoordinates(typeId, pages, goodsVo);
//                return Result.success().put("data", goodsList);
            } else {
                IPage<GoodsVo> goodsList = baseMapper.getGoodsList(pages, goodsVo);
                return Result.success().put("data", goodsList);
            }
        }
        return Result.error("商品经纬度不能为空");
    }

    @Override
    public Result selectTypeByName(String typeName) {
        List<GoodsType> types = new ArrayList<>();
        if (typeName != null && !typeName.isEmpty()) {
            List<GoodsType> goodsTypeAllList = goodsTypeService.list(new QueryWrapper<GoodsType>()
//                    .eq("is_recovery", 0)
                    .eq("is_type", 1));
            // 统一处理大小写问题
            String lowerCaseTypeName = typeName.toLowerCase();
            // 首先查找完全匹配的类型
            List<GoodsType> exactMatch = goodsTypeService.list(new QueryWrapper<GoodsType>()
//                    .eq("is_recovery", 0)
                    .eq("is_type", 1)
                    .like("type_name", '%' + typeName.trim() + '%'));

            if (!exactMatch.isEmpty()) {
                // 如果父级包含"手机"，则展示手机的类型列表
                List<GoodsType> phoneTypes = exactMatch.stream()
//                        .filter(a -> {
                        .map(a -> {
                            if (a.getTypeName().contains("手机")) {
                                return a;
                            }
                            GoodsType parent = goodsTypeDao.selectById(a.getParentId());
                            if (parent != null && parent.getTypeName().contains("手机")) {
                                return parent;
                            }
                            return null;
                        })
                        .distinct() // 去重
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                if (!phoneTypes.isEmpty()) {
                    return Result.success().put("data", Collections.singletonList(phoneTypes.get(0)));
                }
            }

            // 使用正则表达式进行部分匹配
            Pattern pattern = Pattern.compile(Pattern.quote(lowerCaseTypeName), Pattern.CASE_INSENSITIVE);
            List<GoodsType> filteredTypes = goodsTypeAllList.stream()
                    .filter(e -> lowerCaseTypeName.contains(e.getTypeName().toLowerCase()) && e.getParentId() != 0)
//                    .filter()
//                    {
//                        String typeNameLower = e.getTypeName().toLowerCase();
//                        return pattern.matcher(typeNameLower).find() && e.getParentId() != 0;
//                    }
                    .collect(Collectors.toList());
            if (!filteredTypes.isEmpty()) {
                // 如果父级包含"手机"，则展示手机的类型列表
                List<GoodsType> phoneTypes = filteredTypes.stream()
//                        .filter(a -> {
                        .map(a -> {
                            GoodsType parent = goodsTypeDao.selectById(a.getParentId());
                            if (parent != null && parent.getTypeName().contains("手机")) {
                                return parent;
                            }
                            return null;
                        }).filter(Objects::nonNull)
                        .collect(Collectors.toList());
                if (!phoneTypes.isEmpty()) {
                    return Result.success().put("data", phoneTypes);
                }

                // 否则展示当前过滤出的类型列表
                return Result.success().put("data", filteredTypes);
//            List<GoodsType> goodsTypes = goodsTypeDao.listByTypeName(typeName);
//            if (goodsTypes != null && !goodsTypes.isEmpty()) {
//                for (GoodsType goodsType : goodsTypes) {
//                    GoodsType parent = goodsTypeDao.selectById(goodsType.getParentId());
//                    if (parent.getTypeName().contains("手机")){
//                        types.add(parent);
//                        return Result.success().put("data", types);
//                    }
//                    List<GoodsType> goodsTypeList = goodsTypeDao.selectList(new QueryWrapper<GoodsType>().eq("parent_id", goodsType.getParentId()));
//                    return Result.success().put("data", goodsTypeList);
//                }
            } else {
                List<GoodsType> goodsType = goodsTypeService.list(new QueryWrapper<GoodsType>().like("type_name", "其他商品"));
                return Result.success().put("data", goodsType);
            }
        }
        return Result.error("参数不正确");
    }

    @Override
    public Result selectBrandByTypeId(Long typeId, String brandName) {
        GoodsType goodsType = goodsTypeService.getById(typeId);
        if (goodsType != null) {
            List<Brand> brandList = brandDao.selectList(new QueryWrapper<Brand>()
                    .eq("label_id", goodsType.getLabelId())
                    .like(StringUtil.isNotBlank(brandName), "brand_name", '%' + brandName + '%'));
            List<Brand> brands = new ArrayList<>();
            // 如果有符合条件的品牌，则添加到最终列表
            if (brandList != null && !brandList.isEmpty()) {
                brands.addAll(brandList);
                // 查询并添加“其他品牌”
                Brand otherBrands = brandDao.selectOne(new QueryWrapper<Brand>()
                        .like("brand_name", "其他品牌"));
                // 检查是否已经有“其他品牌”，避免重复添加
                boolean containsOtherBrand = brands.stream().anyMatch(brand -> "其他品牌".equals(brand.getBrandName()));
                if (otherBrands != null && !containsOtherBrand) {
                    brands.add(otherBrands);
                }
//            if (brandList != null && !brandList.isEmpty()) {
//                List<Brand> brandLists = brandDao.selectList(new QueryWrapper<Brand>().like("brand_name", "其他品牌"));
//                brands.addAll(brandLists);
                return Result.success().put("data", brands);
            } else {
                List<Brand> brandLists = brandDao.selectList(new QueryWrapper<Brand>().like("brand_name", "其他品牌"));
                return Result.success().put("data", brandLists);
            }
        } else {
            List<Brand> brandLists = brandDao.selectList(new QueryWrapper<Brand>().like("brand_name", "其他品牌"));
            return Result.success().put("data", brandLists);
        }
    }

    @Override
    public Result selectNewOld() {
        List<GoodsDegree> goodsDegrees = goodsDegreeDao.selectList(null);
        if (goodsDegrees != null) {
            return Result.success().put("data", goodsDegrees);
        }
        return Result.error("暂未找到该商品分类");
    }

    @Override
    public Result getGoodsIdBySpec(Long goodId) {
        //查询商品规格信息关联信息
        List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                .eq("goods_id", goodId));
        //解析规格信息
        List<GoodsSpecifications> specificationsList = new ArrayList<>();
        if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
            for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                if (goodsSpecifications != null) {
                    String attributeValues = goodsSpecifications.getAttributeValue();
                    // 使用正则表达式修正字符串中的单引号为双引号
                    attributeValues = attributeValues.replaceAll("'", "\"");
                    // 使用正则表达式将等号替换为冒号
                    attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                    List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                    goodsSpecifications.setAttributes(attributeValuesList);
                    // 解析 sku_value 字段得到一组 attribute_value 的 ID
                    String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                    List<AttributeValue> filteredAttributes = new ArrayList<>();
                    for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                        if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                            attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                            filteredAttributes.add(attribute);
                        }
                    }
                    // 设置过滤后的属性值列表
                    goodsSpecifications.setAttributes(filteredAttributes);
                    // 添加到最终的规格列表中
                    specificationsList.add(goodsSpecifications);
                }
            }
        }
        return Result.success().put("data", specificationsList);
    }

    @Override
    public IPage<GoodsVo> getGoodsListByPrice(Integer page, Integer limit, GoodsVo goodsVo) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        if (goodsVo.getLabelId() == null) {
            // searchType 1.综合排序
            if (goodsVo.getSearchType() != null) {
                if (StringUtils.isNotBlank(goodsVo.getProvince()) || StringUtils.isNotBlank(goodsVo.getCity()) || StringUtils.isNotBlank(goodsVo.getDistrict())) {
//                    // 查找"市"
//                    int cityEnd = goodsVo.getRegionalDetails().indexOf("市");
//                    String city = "";
//                    if (cityEnd != -1){
//                        city = goodsVo.getRegionalDetails().substring(0, cityEnd + 1);// "包含市"
//                    }
//                    int distinctEnd = Math.max(goodsVo.getRegionalDetails().indexOf("区"), goodsVo.getRegionalDetails().indexOf("县"));
//                    String district = "";
//                    if (distinctEnd != -1){
//                        district = goodsVo.getRegionalDetails().substring(cityEnd + 1, distinctEnd + 1);
//                    }
                    goodsVo.setProvince(goodsVo.getProvince());
                    goodsVo.setCity(goodsVo.getCity());
                    goodsVo.setDistrict(goodsVo.getDistrict());
                }
                return baseMapper.getGoodsBySearchList(pages, goodsVo);
            }
//            if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 1) {
//                // subSearchType 1.最近活跃
//                if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // subSearchType 2.离我最近
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 2) {
//                    // longitude经度 latitude纬度
//                    if (goodsVo.getLongitude() != null || goodsVo.getLatitude() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                    // subSearchType 3.信用排序
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 2.时间排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 2) {
//                // timeRange 1.近一周
//                if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 2.近7天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 3.近15天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 4.近30天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 4) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 5.本周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 5) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 6.上周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 6) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 7.本月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 7) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 8.上月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 8) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 9.自定义时间
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 9) {
//                    if (goodsVo.getStartDate() != null && goodsVo.getEndDate() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                }
//                // searchType 3.价格排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 3) {
//                // priceOrder 1.升序
//                if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // priceOrder 2.降序
//                } else if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 4.区域排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 4) {
//                // city市 district区
//                if (goodsVo.getLongitude() != null && goodsVo.getLatitude() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//            }
//            if (goodsVo.getUserId() != null) {
//                searchRecordService.saveRecordInfo(goodsVo.getBrandName(), goodsVo.getUserId());
//            }
            goodsVo.setUserId(null);
//            return baseMapper.getGoodsByIsRecommend(pages, goodsVo);
            return baseMapper.getGoodsByIsRecommendByPrice(pages, goodsVo);
        } else {
//            // searchType 1.综合排序
//            if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 1) {
//                // subSearchType 1.最近活跃
//                if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // subSearchType 2.离我最近
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 2) {
//                    // longitude经度 latitude纬度
//                    if (goodsVo.getLongitude() != null || goodsVo.getLatitude() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                    // subSearchType 3.信用排序
//                } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 2.时间排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 2) {
//                // timeRange 1.近一周
//                if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 2.近7天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 3.近15天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 3) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 4.近30天
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 4) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 5.本周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 5) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 6.上周
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 6) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 7.本月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 7) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 8.上月
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 8) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // timeRange 9.自定义时间
//                } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 9) {
//                    if (goodsVo.getStartDate() != null && goodsVo.getEndDate() != null) {
//                        return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    }
//                }
//                // searchType 3.价格排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 3) {
//                // priceOrder 1.升序
//                if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 1) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                    // priceOrder 2.降序
//                } else if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 2) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // searchType 4.区域排序
//            } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 4) {
//                // city市 district区
//                if (goodsVo.getLongitude() != null && goodsVo.getLatitude() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//            }
            if (goodsVo.getSearchType() != null) {
                if (StringUtils.isNotBlank(goodsVo.getProvince()) || StringUtils.isNotBlank(goodsVo.getCity()) || StringUtils.isNotBlank(goodsVo.getDistrict())) {
//                    // 查找"市"
//                    int cityEnd = goodsVo.getRegionalDetails().indexOf("市");
//                    String city = "";
//                    if (cityEnd != -1){
//                        city = goodsVo.getRegionalDetails().substring(0, cityEnd + 1);// "包含市"
//                    }
//                    int distinctEnd = Math.max(goodsVo.getRegionalDetails().indexOf("区"), goodsVo.getRegionalDetails().indexOf("县"));
//                    String district = "";
//                    if (distinctEnd != -1){
//                        district = goodsVo.getRegionalDetails().substring(cityEnd + 1, distinctEnd + 1);
//                    }
                    goodsVo.setProvince(goodsVo.getProvince());
                    goodsVo.setCity(goodsVo.getCity());
                    goodsVo.setDistrict(goodsVo.getDistrict());
                }
                return baseMapper.getGoodsBySearchList(pages, goodsVo);
            }
            if (goodsVo.getUserId() != null) {
                searchRecordService.saveRecordInfo(goodsVo.getBrandName(), goodsVo.getUserId());
            }
            goodsVo.setUserId(null);
            return baseMapper.getGoodsListByPrice(pages, goodsVo);
        }

    }

    @Override
    public IPage<GoodsVo> getGoodsListByLabel(Integer page, Integer limit, GoodsVo goodsVo) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        // searchType 1.综合排序
//        if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 1) {
//            // subSearchType 1.最近活跃
//            if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 1) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // subSearchType 2.离我最近
//            } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 2) {
//                // longitude经度 latitude纬度
//                if (goodsVo.getLongitude() != null || goodsVo.getLatitude() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // subSearchType 3.信用排序
//            } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 3) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//            }
//            // searchType 2.时间排序
//        } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 2) {
//            // timeRange 1.近一周
//            if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 1) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 2.近7天
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 2) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 3.近15天
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 3) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 4.近30天
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 4) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 5.本周
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 5) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 6.上周
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 6) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 7.本月
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 7) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 8.上月
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 8) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 9.自定义时间
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 9) {
//                if (goodsVo.getStartDate() != null && goodsVo.getEndDate() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//            }
//            // searchType 3.价格排序
//        } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 3) {
//            // priceOrder 1.升序
//            if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 1) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // priceOrder 2.降序
//            } else if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 2) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//            }
//            // searchType 4.区域排序
//        } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 4) {
//            // city市 district区
//            if (goodsVo.getLongitude() != null && goodsVo.getLatitude() != null) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//            }
//        }
        if (goodsVo.getSearchType() != null) {
            if (StringUtils.isNotBlank(goodsVo.getProvince()) || StringUtils.isNotBlank(goodsVo.getCity()) || StringUtils.isNotBlank(goodsVo.getDistrict())) {
//                    // 查找"市"
//                    int cityEnd = goodsVo.getRegionalDetails().indexOf("市");
//                    String city = "";
//                    if (cityEnd != -1){
//                        city = goodsVo.getRegionalDetails().substring(0, cityEnd + 1);// "包含市"
//                    }
//                    int distinctEnd = Math.max(goodsVo.getRegionalDetails().indexOf("区"), goodsVo.getRegionalDetails().indexOf("县"));
//                    String district = "";
//                    if (distinctEnd != -1){
//                        district = goodsVo.getRegionalDetails().substring(cityEnd + 1, distinctEnd + 1);
//                    }
                goodsVo.setProvince(goodsVo.getProvince());
                goodsVo.setCity(goodsVo.getCity());
                goodsVo.setDistrict(goodsVo.getDistrict());
            }
            return baseMapper.getGoodsBySearchList(pages, goodsVo);
        }
        return baseMapper.getGoodsList(pages, goodsVo);
    }

    @Override
    public IPage<GoodsVo> getGoodsListByCity(Integer page, Integer limit, GoodsVo goodsVo) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        if (goodsVo.getLabelId() == null && goodsVo.getTypeId() == null) {
            return baseMapper.getGoodsByIsRecommend1(pages, goodsVo);
        } else {
            return baseMapper.getGoodsListByCity(pages, goodsVo);
        }
    }

    @Override
    public Result selectByType(Long typeId) {
        if (typeId != null) {
            List<GoodsType> goodsTypes = goodsTypeDao.selectList(new QueryWrapper<GoodsType>().eq("parent_id", typeId));
            if (goodsTypes != null && !goodsTypes.isEmpty()) {
                return Result.success().put("data", goodsTypes);
            } else {
                List<GoodsType> goodsTypes1 = goodsTypeDao.selectList(new QueryWrapper<GoodsType>().eq("type_id", typeId));
                if (goodsTypes1 != null) {
                    return Result.success().put("data", goodsTypes1);
                }
            }
        }
        return Result.success();
    }

    @Override
    public Result isTopGoods(Long userId, Long goodId) {
        UserEntity user = userService.selectUserById(userId);
        if (user == null) {
            return Result.error("用户未登录，请登录后再操作");
        }
        Goods goods = baseMapper.selectById(goodId);
        if (goods != null) {
            if (!goods.getUserId().equals(userId)) {
                return Result.error("您没有权限操作");
            }
            if (goods.getStatus() != 1 && goods.getIsEnable() != 1) {
                return Result.error("商品未审核通过或已下架，无法操作");
            }
            // 查询置顶商品的所需金币数
            String topValue = commonInfoService.findOne(518).getValue();
            String[] topValues = topValue.split(",");
            if (topValues.length > 1) {
                int goldNum = Integer.parseInt(topValues[1]);
                if (user.getTotalGold() < goldNum) {
                    return Result.error("您的金币不足，置顶失败");
                }
                user.setTotalGold(user.getTotalGold() - goldNum);
                userService.updateById(user);
                goods.setIsTop(1);
                goods.setTopStartTime(new Date());
                baseMapper.updateById(goods);
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(user.getUserId());
                userMoneyDetails.setTitle("置顶商品");
                userMoneyDetails.setContent("置顶商品扣除的金币：" + goldNum);
                userMoneyDetails.setType(2);
                userMoneyDetails.setClassify(6);
                userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
                GoldRecords goldRecords = new GoldRecords();
                goldRecords.setGoldChange(2);
                goldRecords.setGoldCoins(goldNum);
                goldRecords.setRemark("置顶商品扣除金币");
                goldRecords.setUserId(user.getUserId());
                goldRecords.setRelatedId(goodId);
                goldRecords.setCreateTime(new Date());
                goldRecordsDao.insert(goldRecords);
                return Result.success().put("data", goods);
            }
        }
        return Result.error("该商品不存在，请刷新后重试");
    }

    @Override
    public Result adminIsTopGoods(Long goodId) {
        Goods goods = baseMapper.selectById(goodId);
        if (goods != null) {
            UserEntity user = userService.selectUserById(goods.getUserId());
            if (goods.getStatus() != 1 && goods.getIsEnable() != 1) {
                return Result.error("商品未审核通过或已下架，无法操作");
            }
            // 查询置顶商品的所需金币数
            String topValue = commonInfoService.findOne(518).getValue();
            String[] topValues = topValue.split(",");
            if (topValues.length > 1) {
                int goldNum = Integer.parseInt(topValues[1]);
                if (goods.getIsTop() == 1) {
                    goods.setIsTop(0);
                    baseMapper.updateById(goods);
                } else {
                    if (user.getTotalGold() < goldNum) {
                        return Result.error("该用户的金币不足，置顶失败");
                    }
                    user.setTotalGold(user.getTotalGold() - goldNum);
                    userService.updateById(user);
                    goods.setIsTop(1);
                    goods.setTopStartTime(new Date());
                    baseMapper.updateById(goods);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(user.getUserId());
                    userMoneyDetails.setTitle("置顶商品");
                    userMoneyDetails.setContent("置顶商品扣除的金币：" + goldNum);
                    userMoneyDetails.setType(2);
                    userMoneyDetails.setClassify(6);
                    userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    userMoneyDetailsService.save(userMoneyDetails);
                    GoldRecords goldRecords = new GoldRecords();
                    goldRecords.setGoldChange(2);
                    goldRecords.setGoldCoins(goldNum);
                    goldRecords.setRemark("置顶商品扣除金币");
                    goldRecords.setUserId(user.getUserId());
                    goldRecords.setRelatedId(goodId);
                    goldRecords.setCreateTime(new Date());
                    goldRecordsDao.insert(goldRecords);
                }
                return Result.success().put("data", goods);
            }
        }
        return Result.error("该商品不存在，请刷新后重试");
    }

    @Override
    public IPage<GoodsVo> getGoodsBySearchList(Integer page, Integer limit, GoodsVo goodsVo) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        // 定义正则表达式以匹配32位的十六进制字符串
        Pattern pattern = Pattern.compile("[0-9a-fA-F]{32}");
        // 创建匹配器对象
        Matcher matcher = pattern.matcher(goodsVo.getBrandName());
        // 用于存储找到的所有UUID
//        List<String> uuids = new ArrayList<>();
        while (matcher.find()) {
            // 找到一个匹配项，获取匹配的字符串
            String uuid = matcher.group();
//            // 将UUID添加到列表中
//            uuids.add(uuid);
            goodsVo.setBrandName(uuid);
        }
        // searchType 1.综合排序
//        if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 1) {
//            // subSearchType 1.最近活跃
//            if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 1) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // subSearchType 2.离我最近
//            } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 2) {
//                // longitude经度 latitude纬度
//                if (goodsVo.getLongitude() != null || goodsVo.getLatitude() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//                // subSearchType 3.信用排序
//            } else if (goodsVo.getSubSearchType() != null && goodsVo.getSubSearchType() == 3) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//            }
//            // searchType 2.时间排序
//        } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 2) {
//            // timeRange 1.近一周
//            if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 1) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 2.近7天
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 2) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 3.近15天
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 3) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 4.近30天
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 4) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 5.本周
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 5) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 6.上周
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 6) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 7.本月
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 7) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 8.上月
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 8) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // timeRange 9.自定义时间
//            } else if (goodsVo.getTimeRange() != null && goodsVo.getTimeRange() == 9) {
//                if (goodsVo.getStartDate() != null && goodsVo.getEndDate() != null) {
//                    return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                }
//            }
//            // searchType 3.价格排序
//        } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 3) {
//            // priceOrder 1.升序
//            if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 1) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//                // priceOrder 2.降序
//            } else if (goodsVo.getPriceOrder() != null && goodsVo.getPriceOrder() == 2) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//            }
//            // searchType 4.区域排序
//        } else if (goodsVo.getSearchType() != null && goodsVo.getSearchType() == 4) {
//            // city市 district区
//            if (goodsVo.getLongitude() != null && goodsVo.getLatitude() != null) {
//                return baseMapper.getGoodsBySearchList(pages, goodsVo);
//            }
//        }
        if (goodsVo.getSearchType() != null) {
            if (StringUtils.isNotBlank(goodsVo.getProvince()) || StringUtils.isNotBlank(goodsVo.getCity()) || StringUtils.isNotBlank(goodsVo.getDistrict())) {
//                    // 查找"市"
//                    int cityEnd = goodsVo.getRegionalDetails().indexOf("市");
//                    String city = "";
//                    if (cityEnd != -1){
//                        city = goodsVo.getRegionalDetails().substring(0, cityEnd + 1);// "包含市"
//                    }
//                    int distinctEnd = Math.max(goodsVo.getRegionalDetails().indexOf("区"), goodsVo.getRegionalDetails().indexOf("县"));
//                    String district = "";
//                    if (distinctEnd != -1){
//                        district = goodsVo.getRegionalDetails().substring(cityEnd + 1, distinctEnd + 1);
//                    }
                goodsVo.setProvince(goodsVo.getProvince());
                goodsVo.setCity(goodsVo.getCity());
                goodsVo.setDistrict(goodsVo.getDistrict());
            }
            return baseMapper.getGoodsBySearchList(pages, goodsVo);
        }
        if (goodsVo.getUserId() != null) {
            searchRecordService.saveRecordInfo(goodsVo.getBrandName(), goodsVo.getUserId());
        }
        goodsVo.setUserId(null);
        return baseMapper.getGoodsByIsRecommend(pages, goodsVo);
    }

    @Override
    public Result updateStatusByGoodId(Goods goods) {
        Goods goods1 = baseMapper.selectById(goods.getGoodId());
        if (goods1 == null) {
            return Result.error("商品不存在");
        }
        if (goods1.getIsEnable() == 1) {
            goods.setIsEnable(2);
        } else {
            goods.setIsEnable(1);
        }
        if (baseMapper.updateById(goods) > 0) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @Override
    public Result selectByGoodId(Long goodId) {
        GoodsVo goodsVo = baseMapper.getGoodsById(goodId, null);
//        if (goodsVo == null || goodsVo.getIsEnable() == 0) {
//            return Result.error("该商品已被买走或下架，请刷新后重试");
//        }
//        if (goodsVo.getIsEnable() != 1 || goodsVo.getStatus() != 1) {
//            return Result.error("该商品已下架或状态异常，请刷新后重试！");
//        }
        //查询商品规格信息关联信息
        List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                .eq("goods_id", goodId));
        //解析规格信息
        List<GoodsSpecifications> specificationsList = new ArrayList<>();
        if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
            for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                if (goodsSpecifications != null) {
                    String attributeValues = goodsSpecifications.getAttributeValue();
                    // 使用正则表达式修正字符串中的单引号为双引号
                    attributeValues = attributeValues.replaceAll("'", "\"");
                    // 使用正则表达式将等号替换为冒号
                    attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                    List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                    goodsSpecifications.setAttributes(attributeValuesList);
                    // 解析 sku_value 字段得到一组 attribute_value 的 ID
                    String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                    List<AttributeValue> filteredAttributes = new ArrayList<>();
                    for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                        if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                            attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                            filteredAttributes.add(attribute);
                        }
                    }
                    if (goodsVo.getGoodStatus() == 1) {
                        // 将所有商品规格价格相加，存入这个字段
                        BigDecimal totalPrice = filteredAttributes.stream()
                                .map(attr -> new BigDecimal(attr.getAttPrice()))
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        goodsVo.setGoodPrice(totalPrice);
                    }
                    // 设置过滤后的属性值列表
                    goodsSpecifications.setAttributes(filteredAttributes);
                    // 添加到最终的规格列表中
                    specificationsList.add(goodsSpecifications);
                }
            }
            // 将规格信息添加到 GoodsVo 中
            goodsVo.setSpecifications(specificationsList);
        }
        goodsVo.setBrowseCount(goodsVo.getBrowseCount() + 1);
        baseMapper.updateById(goodsVo);
        return Result.success().put("data", goodsVo);
    }

    @Override
    public boolean selectStockByGoodId(Long goodId, Integer buyNum) {
        Goods goods = baseMapper.selectById(goodId);
        return goods != null && goods.getIsStock() != null && goods.getIsStock() == 2 && goods.getStock() >= buyNum;
    }

    @Override
    public Result updateStockByGoodId(Long goodId, Integer buyNum) {
        if (selectStockByGoodId(goodId, buyNum)) {
            Goods goods = baseMapper.selectById(goodId);
            goods.setStock(goods.getStock() - buyNum);
            baseMapper.updateById(goods);
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    @Override
    public Result updateByStock(Goods goods) {
        Goods goods1 = baseMapper.selectById(goods.getGoodId());
        if (goods1 != null) {
            goods1.setStock(goods.getStock());
            baseMapper.updateById(goods1);
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    @Override
    public Result getGoodsByTypes(Integer page, Integer limit, String typeName) {
        Page<GoodsType> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        List<GoodsType> goodsTypes = goodsTypeDao.selectList(new QueryWrapper<GoodsType>()
                .select("type_name", "type_id")
                .like(StringUtils.isNotBlank(typeName), "type_name", '%' + typeName + '%')
                .eq("parent_id", 0)
                .eq("is_type", 1));
        if (goodsTypes != null && !goodsTypes.isEmpty()) {
            return Result.success().put("data", goodsTypes);
        } else {
            List<GoodsType> goodsTypes1 = goodsTypeDao.selectList(new QueryWrapper<GoodsType>()
                    .like("type_name", "其他商品"));
            if (goodsTypes1 != null && !goodsTypes1.isEmpty()) {
                return Result.success().put("data", goodsTypes1);
            }
            return Result.error("暂未查到");
        }
    }

    @Override
    public int selectByRecycleGoods(Long goodId, Integer status, BigDecimal totalPrice) {
        GoodsVo goodsOne = baseMapper.getGoodsById(goodId, null);
        if (goodsOne != null) {
            String formName = null;
            //查询商品规格信息关联信息
            List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                    .eq("goods_id", goodsOne.getGoodId()));
            //解析规格信息
            // 初始化总价格
//            BigDecimal totalPrice = BigDecimal.ZERO;
            List<GoodsSpecifications> specificationsList = new ArrayList<>();
            List<String> formNameParts = new ArrayList<>(); // 用于存储规格名称的部分
            if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
                for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                    GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                    if (goodsSpecifications != null) {
                        String attributeValues = goodsSpecifications.getAttributeValue();
                        // 使用正则表达式修正字符串中的单引号为双引号
                        attributeValues = attributeValues.replaceAll("'", "\"");
                        // 使用正则表达式将等号替换为冒号
                        attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                        List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                        goodsSpecifications.setAttributes(attributeValuesList);
                        // 解析 sku_value 字段得到一组 attribute_value 的 ID
                        String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                        List<AttributeValue> filteredAttributes = new ArrayList<>();
                        for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                            if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                filteredAttributes.add(attribute);
                                // 收集规格名称到列表中
                                formNameParts.add(attribute.getAttName());
                            }
                        }
                        // 将所有商品规格价格相加
//                        BigDecimal skuTotalPrice = filteredAttributes.stream()
//                                .map(attr -> new BigDecimal(attr.getAttPrice()))
//                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        // 累加到总价格
//                        totalPrice = totalPrice.add(skuTotalPrice);
                        // 设置过滤后的属性值列表
                        goodsSpecifications.setAttributes(filteredAttributes);
                        // 添加到最终的规格列表中
                        specificationsList.add(goodsSpecifications);
                    }
                }
                goodsOne.setGoodPrice(totalPrice);
                // 使用 join 方法拼接规格名称，确保最后一个元素后不带 '/'
                formName = String.join("/", formNameParts);
                goodsOne.setFormName(formName);
            }
            boolean matched = false;
            List<StockManage> stockManages = stockManageDao.selectList(new QueryWrapper<>());
            for (StockManage stock : stockManages) {
                stock.setGoodSku(formName);
                if (matches(stock, goodsOne)) {
                    stock.setGoodTitle(goodsOne.getBrandName() + " " + goodsOne.getRecoveryName());
                    stock.setStock(stock.getStock() + 1);
                    stock.setOutTime(new Date());
                    stockManageDao.updateById(stock);
//                    goodsOne.setStockId(stock.getId());
//                    goodsOne.setIsStock(2);
//                    goodsOne.setIsEnable(0);
//                    goodsOne.setStatus(1);
//                    goodsOne.setStock(1);
//                    goodsOne.setGoodStatus(0);
//                    goodsOne.setRecycleStatus(1);
//                    goodsOne.setStockStatus(1);
//                    baseMapper.updateById(goodsOne);
                    matched = true;
                    break;
                }
            }
            if (!matched) {
//                goodsOne.setIsEnable(0);
//                goodsOne.setStatus(1);
//                goodsOne.setIsStock(2);
//                goodsOne.setStock(1);
//                goodsOne.setRecycleStatus(1);
//                goodsOne.setGoodStatus(0);
//                goodsOne.setGoodPrice(totalPrice);
                StockManage stockManage = new StockManage();
                stockManage.setLabelId(goodsOne.getLabelId());
//                stockManage.setTypeId(goodsOne.getTypeId());
                stockManage.setBrandId(goodsOne.getBrandId());
                stockManage.setRecoveryId(goodsOne.getRecoveryId());
                stockManage.setPutPrice(totalPrice);
                stockManage.setStock(1);
                stockManage.setOutStock(0);
                stockManage.setCreateTime(new Date());
                stockManageDao.insert(stockManage);
//                goodsOne.setStockStatus(1);
//                goodsOne.setStockId(stockManage.getId());
//                baseMapper.updateById(goodsOne);
            }
        }
        return 1;
    }

    private boolean matches(StockManage stockManage, GoodsVo goodsOne) {
        return stockManage.getLabelId().equals(goodsOne.getLabelId()) &&
                stockManage.getBrandId().equals(goodsOne.getBrandId()) &&
                stockManage.getRecoveryId().equals(goodsOne.getRecoveryId()) &&
                stockManage.getPutPrice().equals(goodsOne.getGoodPrice()) &&
                stockManage.getGoodSku() != null && stockManage.getGoodSku().equals(goodsOne.getFormName());
    }

}
